﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using UnityEngine.Video;

[RequireComponent(typeof(RawImage))]
public class DragObj : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler {

	public Vector2 standardRev = new Vector2 (1920, 1080);

    public RawImage img = null;

	public Vector2 initPos = Vector2.zero;
	public Vector2 destPos = Vector2.one;
	Vector2 range = new Vector2(100,100);

	public GameObject FingerBg = null;
	public FingerMove finger = null;


	public Action onDragEndCallback = null;


	public Vector2 size = Vector2.one;

	public RectTransform rectTransform = null;


	// Use this for initialization
	void Start () {

	}

	// 设定参数
	public void Init( string urlImage, Vector2 size, Vector2 beginPos, Vector2 endPos, Action cb )
	{

		this.size = size;

        Vector2 vparam = Vector2.zero;
        if ((Screen.height * 1f / Screen.width > 1080f / 1920) && Screen.height > 1080 )
            vparam = new Vector2(0, (Screen.height - 1080) / 2f - 50);

        this.initPos = beginPos + vparam;
        this.destPos = endPos + vparam;

		rectTransform.sizeDelta = this.size;
		rectTransform.anchoredPosition = initPos;


        finger.Begin (initPos + new Vector2(this.size.x/2f, 0-this.size.y/2f) , destPos );
		ShowFinger (true);
		onDragEndCallback = cb;

        if ( ResLoader.IsHttpUrl(urlImage) )
        {
            ResLoader.Load(urlImage, null,
            (www) => {
                if (string.IsNullOrEmpty(www.error))
                {
                    img.texture = www.texture;
                }
            },
            true, true);
        }


    }

	void OnEnable()
	{
		rectTransform.sizeDelta = this.size;
		rectTransform.anchoredPosition = initPos;

		ShowFinger (true);
	}

		

	void OnEnd()
	{
		if (Functions.isNear (destPos, rectTransform.anchoredPosition, range)) {
		
			// next
			rectTransform.anchoredPosition = destPos;

			if (onDragEndCallback != null)
				onDragEndCallback ();

		} else {
		
			rectTransform.anchoredPosition = initPos;
			ShowFinger (true);
		}
	}


	public void OnBeginDrag(PointerEventData eventData)
	{
		ShowFinger (false);
	}

	public void OnDrag(PointerEventData eventData)
	{

		rectTransform.position = eventData.position;
		Debug.Log (rectTransform.position);
	}

	public void OnEndDrag(PointerEventData eventData)
	{
		OnEnd ();
	}


	public void ShowFinger( bool show )
	{
		finger.gameObject.SetActive (show);
		FingerBg.SetActive (show);
	}

}
